<template>
  <div class="short-video">
    <swiper class="short-video-list"
            :style="{'height':videoHight}"
            :current="videoIndex"
            @animationfinish="handleSlider"
            @change="videoChange"
            :indicator-dots="false"
            :vertical="true">
      <swiper-item class="h100p video-list"
                   v-for="(item,index) in vlist"
                   :key="index">
        <!-- <image class="stop" :class=" isActive ? 'active' : '' " :src="stopImg" mode=""></image> -->
        <ul class="operation">
          <li class="follow-box"
              @click="follow_tag(item)">
            <div class="headPortrait">
              <image :src="item.logo"
                     v-if="item.logo"></image>
              <image :src="logoImg"
                     v-else></image>

            </div>
            <span class="follow"
                  v-if="item.attention == false ">关注</span>
            <span class="follow"
                  v-else>已关注</span>
          </li>
          <li @click="likes_tag(item)">
            <image class="w25 h25 mb5"
                   :src="likedImg"
                   v-if="item.like"></image>
            <image class="w25 h25 mb5"
                   :src="noLikeImg"
                   v-else></image>
            <span class="fs12">{{item.likesNum}}</span>
          </li>
          <li @click="forward_tag(item)">
            <button class="forward"
                    open-type="share">
              <image class="w25 h25 mb5"
                     :src="transpondImg"></image>
              <span class="forwardNum fs12">{{item.forwardNum}}</span>
            </button>
          </li>
          <li class="haveChat"
              @click="talk_tag(item.cardId)">
            <image class=" w25 h25 mb5"
                   :src="talkImg"></image>
            <span class="fs12">聊一聊</span>
          </li>
          <button class="forwarda"
                  open-type="getUserInfo"
                  @getuserinfo="GetUserInfo"
                  v-if="isLogin == false">
          </button>
        </ul>
        <div class="information">
          <div class="title">@{{item.userName}}<span class="fs14 c38 ml10"
                  v-if="item.uploadTime">{{item.uploadTime}}</span></div>
          <div class="introduce">{{item.title}}</div>
          <div class="position">
            <image :src="locationImg"
                   class="w12 h12"></image>
            <p class="position-word">{{item.address}}</p>
          </div>
        </div>
        <video :src="item.url"
               :id="'myVideo' + index"
               :controls="true"
               :loop="true"
               :autoplay="index == videoIndex"
               :show-fullscreen-btn="false"
               objectFit="contain"
               @play="playVideo(item)">
        </video>

      </swiper-item>

    </swiper>
  </div>
</template>

<script>
import WXAJAX from "../utils/request";
import tools from "../utils/index";
import HandleLogin from "@/utils/handleLogin";
import { mapMutations } from "vuex";
export default {
  props: {
    refresh: {
      type: Boolean,
      default: false
    },
    companyId: {
      type: Number,
      default: wx.getStorageSync("COMPANYID")
    }
  },
  data() {
    return {
      statusBarHeight: "",
      videoHight: "",
      navHeight: "",
      stopImg: WXAJAX.imgBackUrl + "/one-product/video-icon/icon_play%402x.png",
      //未点赞
      noLikeImg:
        WXAJAX.imgBackUrl + "/one-product/video-icon/icon_like%402x.png",
      //已点赞
      likedImg:
        WXAJAX.imgBackUrl +
        "/one-product/video-icon/icon_like_selected%402x.png",
      //聊一聊
      talkImg: WXAJAX.imgBackUrl + "/one-product/video-icon/icon_talk%402x.png",
      //转发
      transpondImg:
        WXAJAX.imgBackUrl + "/one-product/video-icon/icon_transpond%402x.png",
      //定位
      locationImg:
        WXAJAX.imgBackUrl + "/one-product/video-icon/icon_location_w%402x.png",
      //默认头像
      logoImg: WXAJAX.imgBackUrl + "/one-product/video-icon/logo.png",
      isActive: false,
      videoContext: [],
      isPlay: false,
      clickCount: 0,
      videoIndex: 0,
      islikes: false,
      vlist: [],
      //currentCompany:wx.getStorageSync('CURRENT_COMPANY') || {},
      isLogin: wx.getStorageSync("isLogin"),
      currentCompany: "",
      videoContextList: [],
      //为true时是点赞 为false时是取消
      videoLeg: "",
      page: 1,
      cardId: wx.getStorageSync("CARDID") || {},
      //判断page是否需要加1
      ispage: true,
      videoId: [],
      wVideo: "",
      //防止swiper抖动
      current2: "",
      userId: wx.getStorageSync("userId") || {},
      videoC: 0
    };
  },
  watch: {
    vlist(newVal, old) {
      //console.log()
      for (var i in newVal) {
        if (newVal[i].videoId !== this.wVideo.videoId) {
          //var list = list.push(newVal[i])
        }
      }
      // newVal = newVal.unshift(this.wVideo)
      //console.log(newVal)
    },
    companyId(newVal, old) {
      // console.log(newVal)
      this.vlist = [];
      //this.getSmallVideo(1,this.companyId)
    }
  },
  mounted() {
    let isLogin = wx.getStorageSync("isLogin");
    if (isLogin == true) {
      this.calculateNavBarHeight();
      this.getTextMessage();
      this.getSmallVideo(1, this.companyId);
    } else {
      wx.showToast({
        title: "该功能需用户登录后才能使用",
        icon: "none"
      });
    }

    //console.log(this.watchingVideo)
  },
  methods: {
    //视频赋值
    setPage() {
      this.page = 1;
      this.v;
      this.vlist = [];
      //this.videoIndex = 0
      console.log(this.videoIndex);
      console.log(this.page);
    },
    getViedo(data) {
      this.wVideo = data;
      console.log(this.wVideo);
      //this.getShortVideoQuery(this.wVideo.videoId)
    },
    //保存当前观看的视频
    ...mapMutations(["setVideo"]),
    calculateNavBarHeight() {
      let menuButtonBounding = wx.getMenuButtonBoundingClientRect();
      wx.getSystemInfo({
        success: res => {
          let statusBarHeight = res.statusBarHeight; //胶囊按钮与顶部的距离
          //console.log(statusBarHeight)
          let navHeight =
            statusBarHeight +
            (menuButtonBounding.top - statusBarHeight) * 2 +
            menuButtonBounding.height; //导航高度
          this.statusBarHeight = statusBarHeight;
          this.navHeight = navHeight - statusBarHeight;
          //console.log(this.navHeight)
        },
        fail(err) {
          //console.log(err);
        }
      });
    },
    videoChange(event) {
      this.videoC = event.detail.current;
    },
    init() {
      //console.log(this.vlist.length)
      for (var i = 0; i < this.vlist.length; i++) {
        this.videoContextList.push(uni.createVideoContext("myVideo" + i, this));
      }
    },
    getSmallVideo(page, companyId) {
      var than = this;
      let data = {
        // this.companyId ||
        userId: this.userId,
        pageNum: page || 1,
        companyId: companyId || 67
      };
      WXAJAX.POST(data, "", "/shortVideo/queryPage").then(data => {
        if (data.list) {
          data.list.forEach(item => {
            item.uploadTime = than.getDateConversion(item.uploadTime);
            item.uploadTime = tools.getFormatTime(item.uploadTime);
          });

          if (this.page == 1) {
            this.vlist = data.list;
            this.videoId = this.vlist[0].videoId;
            this.setVideo(this.videoId);
          } else {
            this.vlist.concat(data.list);
          }
          console.log(this.vlist);
          this.videoLeg = this.vlist.length;
        } else {
          this.ispage = false;
        }
        this.init();
      });
    },
    async getCurrentCompany(id) {
      WXAJAX.POST(
        {
          cardId: id
        },
        "",
        "/businessCard/cardDetails"
      ).then(data => {
        if (data) {
          this.currentCompany = data;
          wx.navigateTo({
            url:
              "../IM/main?userId=" +
              this.currentCompany.userId +
              "&logo=" +
              this.currentCompany.logo +
              "&type=2&cardId=" +
              this.currentCompany.cardId +
              "&name=" +
              this.currentCompany.name +
              "&wxCode=" +
              (this.currentCompany.personalWx || "") +
              "&phone=" +
              this.currentCompany.phone
          });
        }
      });
    },
    getShortVideoQuery(id) {
      WXAJAX.POST(
        {
          videoId: id
        },
        "",
        "/shortVideo/queryById"
      ).then(data => {
        console.log(data);
      });
    },
    //获取swiper高度
    getTextMessage() {
      var than = this;
      uni.getSystemInfo({
        success(res) {
          than.videoHight =
            res.windowHeight - than.statusBarHeight - than.navHeight + 5 + "px";
          //console.log(res.windowHeight)
        }
      });
    },
    updateBrowsingData(data, item, type) {
      var than = this;
      WXAJAX.POST(data, "", "/shortVideo/updateData").then(() => {
        if (type == "likes") {
          //console.log(item)
          if (item.like == true) {
            //console.log(item)
            item.likesNum += 1;
            wx.showToast({
              title: "点赞成功！",
              duration: 1000,
              mask: true
            });
          } else {
            wx.showToast({
              title: "取消点赞",
              duration: 1000,
              icon: "none",
              mask: true
            });
            item.likesNum -= 1;
          }
        } else if (type == "forward") {
          wx.showLoading({
            mask: true
          });
          setTimeout(function() {
            wx.showToast({
              title: "转发成功！",
              duration: 1000,
              icon: "none"
            });
            item.forwardNum++;
          }, 2000);
        }
      });
    },

    stop_tag() {
      this.isActive = !this.isActive;
    },
    //swiper切换事件
    handleSlider(e) {
      if (e.target.source == "autoplay" || e.target.source == "touch") {
        this.current2 = e.detail.current;
      }
      //console.log(this.videoContextList)
      let curIndex = this.current2;

      if (this.videoIndex >= 0) {
        this.videoContextList[this.videoIndex].pause();
        this.videoContextList[this.videoIndex].seek(0);
      }
      if (curIndex === this.videoIndex + 1) {
        //console.log('向下滑动')
        this.videoContextList[this.videoIndex + 1].play();
      } else if (curIndex === this.videoIndex - 1) {
        //console.log('向上滑动')
        this.videoContextList[this.videoIndex - 1].play();
      }
      this.videoIndex = curIndex;
      //console.log(this.videoLeg)
      var vlength = this.videoLeg,
        idx = this.videoIndex;
      if (vlength == idx + 1) {
        if (this.ispage == true && vlength > 1) {
          this.page++;
          this.getSmallVideo(this.page, this.companyId);
        }
      }
      this.videoId = this.vlist[this.videoIndex].videoId;
      this.setVideo(this.videoId);
    },
    // 播放
    play(index) {
      this.videoContextList[index].play();
    },
    // 暂停
    pause(index) {
      this.videoContextList[index].pause();
    },
    //关注
    follow_tag(item) {
      let attentionNum = "";
      console.log(item.attention);
      if (item.attention == false) {
        attentionNum = 1;
      } else if (item.attention == true) {
        attentionNum = 0;
      }
      wx.showLoading({
        mask: true
      });
      WXAJAX.POST(
        {
          attention: attentionNum,
          userId: wx.getStorageSync("userId"),
          videoId: item.videoId
        },
        "",
        "/shortVideo/addAttentionUser"
      ).then(data => {
        wx.hideLoading();
        if (item.attention == false) {
          for (var i in this.vlist) {
            if (this.vlist[i].userId == item.userId) {
              this.vlist[i].attention = true;
            }
          }
          wx.showToast({
            title: "关注成功",
            duration: 1000,
            mask: true
          });
        } else {
          for (var i in this.vlist) {
            if (this.vlist[i].userId == item.userId) {
              this.vlist[i].attention = false;
            }
          }
          wx.showToast({
            title: "取消关注",
            icon: "none",
            duration: 1000,
            mask: true
          });
        }
      });
    },
    //点赞
    likes_tag(item) {
      let likes = "";
      console.log(item.like);
      if (item.like == false) {
        likes = true;
      } else if (item.like == true) {
        likes = false;
      }
      wx.showLoading({
        mask: true
      });
      WXAJAX.POST(
        {
          like: likes,
          userId: wx.getStorageSync("userId"),
          videoId: item.videoId
        },
        "",
        "/shortVideo/addAttentionUser"
      ).then(data => {
        wx.hideLoading();
        if (item.like == false) {
          item.like = true;
          item.likesNum += 1;
          wx.showToast({
            title: "点赞成功",
            duration: 1000,
            mask: true
          });
        } else {
          item.like = false;
          item.likesNum -= 1;
          wx.showToast({
            title: "取消点赞",
            icon: "none",
            duration: 1000,
            mask: true
          });
        }
      });

      // item.like = !item.like
      // // wx.showLoading({
      // //   mask:true
      // // })
      // let data = {
      //   likesNum:1,
      //   state:item.state,
      //   islikes:item.like,
      //   videoId:item.videoId
      // }
      // let type = 'likes'
      // this.updateBrowsingData(data,item,type)
    },
    //转发
    forward_tag(item) {
      // wx.showLoading({
      //   mask:true
      // })
      let data = {
        forwardNum: 1,
        state: item.state,
        videoId: item.videoId
      };
      var type = "forward";
      this.updateBrowsingData(data, item, type);
    },
    //聊一聊
    talk_tag(cardId) {
      if (cardId == 0 || "") {
        wx.showToast({
          title: "该用户暂无聊天权限",
          icon: "none"
        });
        return false;
      }
      this.getCurrentCompany(cardId);
    },

    //增加播放次数
    playVideo(item) {
      let data = {
        playVolume: 1,
        state: item.state,
        videoId: item.videoId
      };
      this.updateBrowsingData(data, item);
    },
    //解决ios时间格式兼容问题
    getDateConversion(data) {
      let phoneSystem = "";
      wx.getSystemInfo({
        success: function(res) {
          phoneSystem = res.system;
        }
      });
      if (phoneSystem.indexOf("iOS") != -1) {
        data = data.replace(/-/g, "/");
      }
      return Date.parse(data);
    },
    GetUserInfo(e) {
      let _v = this;
      const msg = e.target;
      if (!msg.rawData || !msg.signature || !msg.encryptedData || !msg.iv) {
        return;
      }
      HandleLogin.login(data => {
        HandleLogin.setLoginMessageInStorage(data, false);
        this.isLogin = true;
        this.getSmallVideo(this.page, companyId);
      });
    }
  },
  onReachBottom: function() {
    //console.log(111)
    if (timer != null) {
      clearTimeout(timer);
    }
    timer = setTimeout(function() {}, 1000);
  }
};
</script>

<style scoped>
.shortVideo {
  height: 100%;
  display: flex;
  box-sizing: border-box;
}
.short-video-list {
  box-sizing: border-box;
  position: relative;
}
.stop {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  width: 160upx;
  height: 160upx;
}
.information {
}
.video-list {
  position: relative;
}
.video-list video {
  width: 100%;
  height: 100%;
}
.operation {
  position: absolute;
  right: 15upx;
  bottom: 70upx;
  display: flex;
  flex-direction: column;
  width: 98upx;
  height: 550upx;
  justify-content: space-between;
  z-index: 99;
}
.operation li {
  width: 98upx;
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 123upx;
}
.haveChat {
  position: relative;
}
.forwarda {
  width: 100%;
  height: 100%;
  position: absolute;
  bottom: 0;
  z-index: 100;
  background: rgba(56, 56, 56, 0);
}
.follow-box {
  height: 98upx;
  width: 98upx;
  position: relative;
}
.follow {
  position: absolute;
  z-index: 99;
  display: block;
  height: 30upx;
  width: 80upx;
  background: #51cdcb;
  bottom: 0;
  margin-left: 7upx;
  text-align: center;
  border-radius: 15upx;
  left: 5upx;
  font-size: 20upx;
  color: #ffffff;
}
.headPortrait {
  width: 101upx;
  height: 101upx;
  border-radius: 50%;
  border: 8upx solid #ffffff;
}
.headPortrait image {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}
.information {
  position: absolute;
  left: 30upx;
  z-index: 99;
  bottom: 100upx;
}
.title {
  margin-bottom: 30upx;
  color: #ffffff;
  font-size: 32upx;
  font-weight: 600;
}
.introduce {
  width: 458upx;
  height: 80upx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  font-size: 32upx;
  color: #ffffff;
  margin-bottom: 50upx;
}
.position {
  height: 40upx;
  background: rgba(118, 118, 118, 0.15);
  box-shadow: 0px 1px 4px 0px rgba(56, 56, 56, 0.3);
  border-radius: 20upx;
  display: flex;
  color: #ffffff;
  align-items: center;
  padding: 8upx 20upx;
  float: left;
}
.position-word {
  display: block;
  max-width: 450upx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.position image {
  margin-right: 9upx;
}
.active {
  z-index: 99;
}
.forward {
  background: rgba(255, 255, 255, 0);
  height: 103upx !important;
  position: relative;
  color: #ffffff;
}
.forwardNum {
  position: absolute;
  bottom: 0;
  left: 41upx;
}
</style>
